package com.example.data.factory.web1.controller;

import com.example.data.factory.common.result.R;
import com.example.data.factory.entity.entity.Script;
import com.example.data.factory.service.service.ScriptService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/upload")
public class FileUploadController {
    /**
     * 上传 Python 文件
     */
    @Resource
    private ScriptService scriptService;

    @PostMapping("/python")
    public R<?> uploadPythonFile(@RequestParam("file") MultipartFile file) {
        try {
            // 检查文件是否为空
            if (file == null || file.isEmpty ()) {
                return R.Failed ( "请上传一个有效的 Python 文件" );
            }

            // 获取文件名并检查扩展名
            String fileName = file.getOriginalFilename ();
            if (fileName == null || !fileName.toLowerCase ().endsWith ( ".py" )) {
                return R.Failed ( "文件类型错误，仅支持上传 .py 文件" );
            }

            // 定义文件存储路径
            String filePath = System.getProperty ( "user.dir" ) + File.separator + "uploads" + File.separator + fileName;

            // 确保上传目录存在
            File uploadDir = new File ( System.getProperty ( "user.dir" ) + File.separator + "uploads" );
            if (!uploadDir.exists ()) {
                uploadDir.mkdirs ();
            }
            // 保存文件到指定路径
            file.transferTo ( new File ( filePath ) );
            Script script = new Script ();
            script.setScriptFileUrl ( filePath );
            scriptService.save ( script );
            return R.Success ( "Python 文件上传成功: " + fileName );
        } catch (IOException e) {
            return R.Failed ( "文件上传失败: " + e.getMessage () );
        }
    }

}
